<script setup lang="ts">
import { ref } from 'vue';

import { JsonViewer, useVbenModal } from '@vben/common-ui';

// JsonPreview
import { tslExport } from '#/api/iot/product/thingModel';

const tslView = ref('');
const id = ref('');

const [BasicModal, modalApi] = useVbenModal({
  fullscreenButton: false,
  showCancelButton: false,
  showConfirmButton: false,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    modalApi.modalLoading(true);
    const { tsl, productId } = modalApi.getData() as {
      productId: string;
      tsl: string;
    };
    tslView.value = tsl;
    id.value = productId;

    modalApi.modalLoading(false);
  },
});

async function handleExport() {
  const res = await tslExport(id.value);

  const blob = new Blob([res], {
    type: 'application/json',
  });
  // 创建临时下载链接
  const url = URL.createObjectURL(blob);

  // 创建一个虚拟链接并触发点击事件以下载文件
  const a = document.createElement('a');
  a.href = url;
  a.download = 'TSL.json'; // 设置下载的文件名
  a.click();

  // 释放 URL 对象
  URL.revokeObjectURL(url);
}
</script>

<template>
  <BasicModal title="查看物模型" class="w-[550px]">
    <JsonViewer
      :value="JSON.parse(tslView)"
      copyable
      :sort="false"
      theme="monokai"
      boxed
      expanded
      preview-mode
      show-double-quotes
    />
    <template #footer>
      <a-button type="primary" @click="handleExport">导出模型文件</a-button>
    </template>
  </BasicModal>
</template>
